import flet as ft
from tools.image_utils import resize_image


class ImageToolsUI:
    def __init__(self, page, show_main_menu):
        self.page = page
        self.show_main_menu = show_main_menu
        self.setup_ui()

    def setup_ui(self):
        # 图像路径输入框
        self.image_path = ft.TextField(label="图像路径", hint_text="请输入图像路径")
        self.width_input = ft.TextField(label="宽度", hint_text="请输入宽度")
        self.height_input = ft.TextField(label="高度", hint_text="请输入高度")

        # 执行按钮
        self.resize_button = ft.ElevatedButton(
            text="调整大小",
            on_click=self.on_resize_button_click,
        )

        # 返回主菜单按钮
        self.back_button = ft.ElevatedButton(
            text="返回主菜单",
            on_click=lambda e: self.show_main_menu(),  # 使用 lambda 忽略事件参数
        )

        # 结果输出
        self.result_text = ft.Text()

    def build(self):
        return ft.Column(
            controls=[
                ft.Text("图像工具", size=20),
                self.image_path,
                self.width_input,
                self.height_input,
                self.resize_button,
                self.back_button,
                self.result_text,
            ],
            spacing=20,
        )

    def on_resize_button_click(self, e):
        image_path = self.image_path.value
        width = self.width_input.value
        height = self.height_input.value

        if not image_path or not width or not height:
            self.result_text.value = "请输入图像路径、宽度和高度！"
            self.page.update()
            return

        try:
            width = int(width)
            height = int(height)
            success, message = resize_image(image_path, width, height)
            self.result_text.value = message
        except ValueError:
            self.result_text.value = "宽度和高度必须为整数！"
        except Exception as ex:
            self.result_text.value = f"操作失败：{str(ex)}"

        self.page.update()
